package com.cunzhang.server.service.impl;

import com.cunzhang.common.constants.JwtClaimsConstant;
import com.cunzhang.common.constants.MessageConstant;
import com.cunzhang.common.constants.StatusConstant;
import com.cunzhang.common.contexts.BaseContext;
import com.cunzhang.common.exception.AccountNotFoundException;
import com.cunzhang.common.exception.LoginFailedException;
import com.cunzhang.common.properties.JwtProperties;
import com.cunzhang.common.result.PageResult;
import com.cunzhang.common.utils.JwtUtil;
import com.cunzhang.pojo.dto.EmployeeDTO;
import com.cunzhang.pojo.dto.EmployeeLoginDTO;
import com.cunzhang.pojo.dto.PasswordDTO;
import com.cunzhang.pojo.entity.Employee;
import com.cunzhang.pojo.vo.EmployeeLoginVO;
import com.cunzhang.server.mapper.EmployeeMapper;
import com.cunzhang.server.service.EmployeeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登录接口
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        Employee queryCondition = new Employee();
        queryCondition.setUsername(employeeLoginDTO.getUsername());

        //获取用户并校验密码
//        Employee employee = employeeMapper.selectEmployeeByUsername(employeeLoginDTO.getUsername());
        List<Employee> employeeList = employeeMapper.selectEmployee(queryCondition);
        if(employeeList == null || employeeList.isEmpty()){
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        Employee employee = employeeList.get(0);
        if(employee == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //被锁定
        if(employee.getStatus().equals(StatusConstant.DISABLE)){
            throw new RuntimeException(MessageConstant.ACCOUNT_LOCKED);
        }

        String password = employeeLoginDTO.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!password.equals(employee.getPassword())){
            throw new LoginFailedException(MessageConstant.PASSWORD_ERROR);
        }

        //创建vo与拷贝属性
        EmployeeLoginVO employeeLoginVO = new EmployeeLoginVO();
        BeanUtils.copyProperties(employee, employeeLoginVO);

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());


        //创建jwt令牌
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        employeeLoginVO.setToken(token);

        return employeeLoginVO;
    }

    /**
     * 员工分页查询接口
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult pageQueryEmployee(String name, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        Page<Employee> employeePage = employeeMapper.pageQueryEmployee(name);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(employeePage.getTotal());
        pageResult.setRecords(employeePage.getResult());

        return pageResult;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置状态
        employee.setStatus(StatusConstant.ENABLE);

        //设置默认密码
        String password = "123456";
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        employee.setPassword(password);

        employeeMapper.insertEmployee(employee);
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     */
    @Override
    public void changeAccountStatus(Integer status, Long id) {
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee queryEmployeeById(Long id) {
        Employee employee = new Employee();
        employee.setId(id);
        List<Employee> list = employeeMapper.selectEmployee(employee);
        return list.get(0);
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void editEmployeeInfo(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.updateEmployee(employee);

    }

    /**
     * 修改密码
     * @param passwordDTO
     */
    @Override
    public void editPassword(PasswordDTO passwordDTO) {
        String oldPassword = DigestUtils.md5DigestAsHex(passwordDTO.getOldPassword().getBytes());
        String newPassword = DigestUtils.md5DigestAsHex(passwordDTO.getNewPassword().getBytes());
        if(oldPassword.equals(newPassword)){
            throw new RuntimeException(MessageConstant.SAME_NEW_PASSWORD);
        }

        Employee queryCondition = new Employee();
        queryCondition.setId(BaseContext.getCurrentId());
        List<Employee> employeeList = employeeMapper.selectEmployee(queryCondition);
        if(employeeList == null || employeeList.size() == 0){
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if(employeeList.size() > 1){
            //无法确定唯一的用户
            throw new RuntimeException(MessageConstant.UNKNOWN_ERROR);
        }

        Employee employee = employeeList.get(0);
        if(!oldPassword.equals(employee.getPassword())){
            throw new RuntimeException(MessageConstant.WRONG_OLD_PASSWORD);
        }

        employee.setPassword(newPassword);
        employeeMapper.updateEmployee(employee);
    }
}
